package dao.impl;

import dao.UserDao;
import pojo.User;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class UserDaoImpl implements UserDao {
    public List<User> findAll() {
        //dao层数据类写在这里
        List<User> users = new ArrayList<>();//用户数据存在集合中
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2.获取连接(url username password)
            String url = "jdbc:mysql://127.0.0.1:3306/jdbc?characterEncoding=utf-8";
            connection = DriverManager.getConnection(url, "root", "20050324");
            //3.写sql
            String sql = "select * from sys_user";
            //4.预编译sql
            preparedStatement = connection.prepareStatement(sql);
            //5.有参数设置参数
            //6.执行sql
             resultSet = preparedStatement.executeQuery();
            //7.遍历结果集
            while (resultSet.next()) {
                //封装数据
                User user = new User();
                user.setId(resultSet.getInt(1));//关联到对应属性
                user.setName(resultSet.getString(2));
                user.setPass(resultSet.getString(3));//关联到对应属性
                users.add(user);//把对象添加到集合中
            }
            //返回集合

//            //8.关闭资源
//            resultSet.close();//修改操作会多这一步
//            preparedStatement.close();
//            connection.close();

            //       return null;
        }catch (ClassNotFoundException e){
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            //8.关闭资源
            try {
                if(resultSet!=null){
                    resultSet.close();
                }
                if(preparedStatement != null){
                    preparedStatement.close();
                }
                if(connection!= null){
                    connection.close();
                }
            }catch (SQLException e){
                throw new RuntimeException(e);
            }
        }
        return users;
    }

}
